<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 视频管理
 */
class Video extends Backend
{
    /** @var \app\admin\model\Video */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Video;
    }

    public function index()
    {
        $this->relationSearch = true;
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            // Selectpage 透传
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 仅显示当前栏目 cate_id 的视频
            $cateId = (int)$this->request->get('cate_id', 0);
            // 统计总数（联表以确保条件与别名一致）
            $countQuery = $this->model->alias('video')
                ->join('__VCATE__ vc', 'vc.id = video.vcate_id', 'LEFT')
                ->where($where);
            if ($cateId > 0) {
                $countQuery->where('video.cate_id', '=', $cateId);
            }
            $total = $countQuery->count();
            $list = [];
            if ($total > 0) {
                $list = $this->model->alias('video')
                    ->join('__VCATE__ vc', 'vc.id = video.vcate_id', 'LEFT')
                    ->field('video.*, vc.title AS vcate_title')
                    ->where($where);
                if ($cateId > 0) {
                    $list->where('video.cate_id', '=', $cateId);
                }
                $list = $list->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            return json(["total" => $total, "rows" => $list]);
        }
        // 传递 cate_id 给前端用于新增编辑
        $this->view->assign('cate_id', (int)$this->request->get('cate_id', 0));
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $cateId = (int)$this->request->get('cate_id', 0);
            $this->view->assign('cate_id', $cateId);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        // timestamps
        $now = time();
        $params['createtime'] = $params['createtime'] ?? $now;
        $params['updatetime'] = $params['updatetime'] ?? $now;

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $this->view->assign('cate_id', (int)$row['cate_id']);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        // timestamp
        $params['updatetime'] = time();
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}


